package cn.edu.usst.cs.wget01;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;

@WebServlet(name = "downloadServlet", value = "/download-servlet")
public class DownloadServlet extends HttpServlet {
    private String message;
    private final String CONTENT_TYPE = "";
    private  String filename = "totoro.png";

    public void init() {
        message = "资源未找到";
//        filename="gradle-8.7-bin.zip";
        filename="1.deb";

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        VERIFY_ORIGIN:
        {
            String referer = request.getHeader("referer");
            System.out.println("referer:\t" + referer);
            if (referer == null) break VERIFY_ORIGIN;
            if (!is_valid_site(referer)) break VERIFY_ORIGIN;
            // 获得输出流对象
            ServletContext context = getServletContext();
            // 返回输入流对象
            InputStream is = context.getResourceAsStream("/images/" + filename);
            if (is != null) {
                // 设置Content-Disposition响应头，指定文件名
                doSend(response, is);
                return;
            }
            error(response, message);
            return;
        }
        request.getRequestDispatcher("protect.jsp").forward(request, response);
//        error(response, "请勿盗取");


    }

    public void doSend(HttpServletResponse response, InputStream inputStream) throws IOException {
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("image/jpeg");
        response.setContentType("application/octet-stream");

        send(inputStream, response.getOutputStream());
    }

    public void error(HttpServletResponse response, CharSequence message) throws IOException {
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        try (Writer writer = response.getWriter()) {
            writer.write(message.toString());
        }
    }

    private void send(@NotNull InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int total = 0;
        int bytesread;
        while (true) {
            bytesread = inputStream.read(buffer);
            if (bytesread == -1) break;
            total += bytesread;
            outputStream.write(buffer, 0, bytesread);
        }
        System.out.println(total + "_sent");
        outputStream.flush();
        inputStream.close();
    }

    private boolean is_valid_site(String url) {
        if (url == null) return false;
        if (url.isEmpty()) return false;
        String root_site = "wget01_war_exploded";
        boolean got_root = false;
        for (String node : url.split("/")) {
            if (got_root) {
                if ("".equals(node)) return true;
                return node.equals("index.jsp");
            }
            if (node.equals(root_site)) got_root = true;
        }
        return got_root;
    }

    public void destroy() {
    }
}